import {
  FileTransfer,
  FileTransferObject,
  FileUploadOptions
} from '@ionic-native/file-transfer';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { Component } from '@angular/core';
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController,
  LoadingController,
  ActionSheetController
} from 'ionic-angular';
import { BaseUI } from '../../../common/baseUI';
import { MySeriveProvider } from '../../../providers/my-serive/my-serive';
import { Events } from 'ionic-angular';
import { Platform } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-change-avatar',
  templateUrl: 'change-avatar.html'
})
export class ChangeAvatarPage extends BaseUI {
  fileTransfer: FileTransferObject = this.transfer.create();
  path;
  newPath;
  user;

  //拍照上传之后图片返回的地址
  photoReturnUrl = '';
  pictures: any = [];
  //预览图片的地址
  picturesFullPath: any = [];
  picturesTemp;
  isMe = true;
  userId;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public camera: Camera,
    public transfer: FileTransfer,
    public toastCtrl: ToastController,
    public actionSheetCtrl: ActionSheetController,
    public loadingCtrl: LoadingController,
    public mySerive: MySeriveProvider,
    public events: Events,
    public plt: Platform
  ) {
    super();
    this.photoReturnUrl = this.navParams.get('avatar');
  }

  ionViewDidLoad() {}

  ionViewWillLeave() {
    this.complete();
    this.getInfo(); 
  }

  getInfo() {
    const loading = this.showLoading(this.loadingCtrl, '加载中');
    this.mySerive.MeInfo().subscribe(data => {
      // 把服务器对象传值给对象 初始化类型是必须是对象
      this.user = data;
      loading.dismiss();
    });
  }

  // 退出页面并且上传
  complete() {
    const stringuser = JSON.stringify({
      avatar: this.newPath
    });
    this.mySerive.updataImg(stringuser).subscribe( data =>{
      // console.log(data);
    },
    err => {
      // console.log(err);
      }
    );
  }

  // / 放大图片
  zoomImage(index) {
    this.navCtrl.push('SlidePhotoPage', {
      i: index,
      photo: this.picturesFullPath
    });
  }

  //头像上传成功之后触发
  pickPictures($event) {
    // console.log($event);
    
    //$event[0] 图片上传之后服务器返回的数据
    this.pictures = $event.pictures;
    this.photoReturnUrl = this.pictures[0].data;
    this.newPath = this.photoReturnUrl;
  }

  //删除图片触发
  deletedPictures($event) {
    this.photoReturnUrl = null;
  }
}
